package com.kamistoat.meimeichat.meimeichatserverapplication.netty.handlers;

import com.alibaba.fastjson.JSON;
import com.kamistoat.meimeichat.meimeichatserverapplication.entity.MmcUserEntity;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.NettyServerBizHandler;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.service.NettyUserService;
import com.kamistoat.meimeichatserveraggrement.protocol.login.LoginResponse;
import com.kamistoat.meimeichatserveraggrement.protocol.login.ReconnectRequest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 重连接Handler。也可以认为是刷新，重新获取一遍所有的信息，保持数据最新
 * 将当前用户重新执行一遍登录流程即可
 */
@Component
@ChannelHandler.Sharable
public class ReconnectHandlerServer extends NettyServerBizHandler<ReconnectRequest> {
    @Autowired
    NettyUserService nettyUserService;

    /**
     * @param channel
     * @param reconnectRequest
     * @Warning:子类只需要重写该方法
     */
    @Override
    public void channelRead(Channel channel, ReconnectRequest reconnectRequest) {
        if(reconnectRequest == null) return;
        logger.info("断线重连请求处理: " + JSON.toJSONString(reconnectRequest));
        MmcUserEntity selfUserEntity = nettyUserService.queryUserInfo(reconnectRequest.getUserId());
        LoginResponse loginResponse = nettyUserService.getLoginResponse(channel, selfUserEntity);
        channel.writeAndFlush(loginResponse);
    }
}
